# -*- coding:utf-8 -*-
from django.db import models
from django.contrib.auth.models import User

# note on all fiels must be optional
class Unit(User):
    about = models.TextField(u'О себе', blank=True)

class Squad(models.Model):
    is_active = models.BooleanField(default=True)
    name = models.CharField(u'Имя', max_length=200, null=False)
    leader = models.ForeignKey(User, unique=True, related_name='leader')
    members = models.ManyToManyField(User, null = True, related_name='members')

    def __unicode__(self):
        return self.name

class SquadJoinRequest(models.Model):
    user = models.ForeignKey(User)
    squad = models.ForeignKey(Squad)
    team_accepted = models.BooleanField(default=False)
    user_accepted = models.BooleanField(default=False)

class GameAbstract(models.Model):
    title = models.CharField(u'Название', max_length=200, null=False)
    created_timestamp = models.DateTimeField(auto_now_add = True)
    changed_timestamp = models.DateTimeField(auto_now = True)

    def __unicode__(self):
        return self.title

class Game(GameAbstract):
    GAME_STYLES = (
        (u'linear',  u'Линейная'),
        (u'classic', u'Классическая'),
        (u'flags',   u'Флаги'),
        )
    GAME_LEAGUES = (
        (u'high',  u'высшая'),
        (u'first', u'первая'),
#        (u'', u''),
        )

    slug               = models.SlugField(u'Слаг', editable=False)
#    start_timestamp    = models.DateTimeField(u'Старт в')
#    end_timestamp      = models.DateTimeField(u'Окончание в', null=True)
    authors            = models.ManyToManyField(User, related_name = 'author')
#    credit_to          = models.ForeignKey(Squad, related_name = 'credit', null=True)
#    radius             = models.PositiveSmallIntegerField(u'Радиус', null=True)
#    style              = models.CharField(u'Тип игры', max_length = 20, choices = GAME_STYLES, default = 'linear')
#    league             = models.CharField(u'Лига', max_length = 20, choices = GAME_LEAGUES, default = 'first')
    description        = models.TextField(u'Описание', null=True)
#    comments           = models.TextField(u'Комментарии', null=True)
#    attributes         = models.TextField(u'Принадлежности', null=True)
#    registered_squads  = models.ManyToManyField(Squad, null=True, editable=False, related_name = 'registered_squads')
    registered_units  = models.ManyToManyField(Unit, null=True, editable=False, related_name = 'games')

# Задание
class Task(GameAbstract):
    levelnum = models.PositiveSmallIntegerField(u'Номер уровня', null = False, blank = False)
    required = models.PositiveSmallIntegerField(u'Обязателен к прохождению', default = 1)
    timeout = models.TimeField(u'Таймаут', null = False, blank = False)
    text = models.TextField(u'Текст задания', blank=False)
    comment = models.TextField(u'Комментарий к заданию', null=True, editable = False, default='')
    aftersolve_text = models.TextField(u'Текст после прохождения', null=True, editable=False, default='')
    game = models.ForeignKey(Game, related_name='tasks', editable=False)

    def generate_keys(self):
        key = Key(task = self, text = '')
        key.save()

    def get_hints(self, timeshift):
        # returns hint list in appropriate timeshift
        pass

    def check_key(self, string):
        pass

class Key(models.Model):
    text = models.CharField(u'Ключ', max_length = 20, null = False)
    task = models.ForeignKey(Task, related_name='keys')

    def __unicode__(self):
        return self.text

# Подсказка
class Hint(GameAbstract):
    time_shift = models.TimeField(u'Выдать через', null = False, blank = False)
    text = models.TextField(u'Текст')
    task = models.ForeignKey(Task, related_name='hints')

    class Meta:
        unique_together = (('time_shift', 'task'),)

class GameEngine(models.Model):
#    squad = models.ForeignKey(Squad)
    unit = models.ForeignKey(Unit, related_name = 'engine') # squad in future
    game = models.ForeignKey(Game, editable=False)
    created_timestamp = models.DateTimeField(auto_now_add = True)

class TaskEngine(models.Model):
    game_engine = models.ForeignKey(GameEngine)
    task = models.ForeignKey(Task)
    started_timestamp = models.DateTimeField(auto_now_add = True)
    solved_timestamp = models.DateTimeField(null = True)

'''
EventLog:
    game, where it occurs
    event time
    event type

    types:
      hintgot - link to hint
      taskgot - link to task
      keystroke succsessful and not - string if not, link to Key if yes.
    

сценарий как сделать хорошо:

* пользователь вошел в игру
* вычислить текущий уровень
  * посмотреть список уровней игры, исключив из него все решенные. Выбрать первый нерешенный.
* взять текст уровня из базы
* вычислить какие подсказки надо показать
  * посмотреть сколько времени прошло с момента получения задания
  * выбрать все подсказки, которые уже должны быть показаны
* показать текущий уровень, подсказки


gm = new Unit.GameManager(Game) # an equvivalent to join theGame

task_list = gm.tasks()
hint_list = gm.hints()
boolean   = gm.keystroke(String)

class GameManager():

    def __init__(self):
        create record

    def tasks(self):
        select first of the tasks that is not done

    def hints(self):
        hints = []
        for task in self.tasks:
            push hints, task.get_hints(task.started_timestamp)

    def keystroke(self, string):
        for task in self.tasks:
            if task.check_keys(string):
                task.solved_timestamp(Now)
                task.save()
                return True
        return False

'''
